<script setup lang="ts">
import { ImageViewer } from "@/components/common/ImageViewer";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { PureTableBar } from "@/components/RePureTableBar";
import { getToken } from "@/utils/auth";
import Delete from "@iconify-icons/ep/delete";
import EditPen from "@iconify-icons/ep/edit-pen";
import Refresh from "@iconify-icons/ep/refresh";
import AddFill from "@iconify-icons/ri/add-circle-line";
import { onMounted, ref } from "vue";
import tree from "./tree.vue";
import { useUser } from "./utils/hook";
defineOptions({
  name: "Goods"
});

const handleScroll = event => {
  console.log("handleScroll", event);
  console.log("handleScroll", event.target.scrollLeft);
  const scrollLeft = event.target.scrollLeft;
  if (specTableWidht.value >= event.target.clientWidth - 5) {
    return;
  }
  if (scrollLeft > 0) {
    specTableLeft.value = 78 + scrollLeft;
    specTableWidht.value = 556 - scrollLeft;
  } else {
    specTableLeft.value = 78;
    specTableWidht.value = 556;
  }
  console.log("final", specTableWidht.value);
};

const iconHide = ({ row }) => {
  if (row.goodsSpecList.length == 0 || row.goodsSpecList.length == 1) {
    return "icon-no";
  }
};

const treeRef = ref();
const formRef = ref();
const uploadRef = ref();
const tableRef = ref();
const specTableLeft = ref(78);
const specTableWidht = ref(556);
const {
  form,
  loading,
  columns,
  childColumns,
  dataList,
  treeData,
  treeLoading,
  pagination,
  deviceDetection,
  selectData,
  selectedNum,
  onSearch,
  resetForm,
  loadTree,
  openDialog,
  onTreeSelect,
  handleDelete,
  handleDeleteSpec,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  changeBrandPrice,
  showOptLog,
  onBatchStart,
  downTemp,
  beforeUpload,
  handleUpload
} = useUser(tableRef, treeRef, uploadRef);

onMounted(() => {
  // nextTick(() => {
  //   var scrollContainer = document.querySelector(
  //     ".goods-table .pure-table > .el-table"
  //   );
  //   scrollContainer.addEventListener("scroll", handleScroll, true);
  // });
});
</script>

<template>
  <div>
    <div :class="['flex', 'justify-between', deviceDetection() && 'flex-wrap']">
      <tree
        ref="treeRef"
        :class="['mr-[10px]', deviceDetection() ? 'w-full' : 'min-w-[220px]']"
        :treeData="treeData"
        :treeLoading="treeLoading"
        @tree-select="onTreeSelect"
        @load-tree="loadTree"
      />
      <div
        :class="[
          deviceDetection() ? ['w-full', 'mt-2'] : 'w-[calc(100%-230px)]'
        ]"
      >
        <el-form
          ref="formRef"
          :inline="true"
          :model="form"
          class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px] overflow-auto"
        >
          <el-form-item label="商品编码：" prop="goodsCode">
            <el-input
              v-model="form.goodsCode"
              placeholder="请输入"
              clearable
              class="!w-[180px]"
            />
          </el-form-item>
          <el-form-item label="商品名称：" prop="goodsName">
            <el-input
              v-model="form.goodsName"
              placeholder="请输入"
              clearable
              class="!w-[180px]"
            />
          </el-form-item>
          <el-form-item label="商品状态：" prop="goodsStatus">
            <!-- 商品状态 0停用 1启用 -->
            <el-select
              v-model="form.goodsStatus"
              placeholder="请选择"
              clearable
              class="!w-[180px]"
            >
              <el-option label="已启用" value="1" />
              <el-option label="已停用" value="0" />
            </el-select>
          </el-form-item>

          <el-form-item label="商品标签：" prop="labelIdList">
            <el-tree-select
              v-model="form.labelIdList"
              class="!w-[180px]"
              default-expand-all
              multiple
              clearable
              node-key="id"
              :collapse-tags="form.labelIdList && form.labelIdList.length > 3"
              :data="selectData.labelList"
            />
          </el-form-item>
          <el-form-item label="关联供应商：" prop="supplierId">
            <el-select
              v-model="form.supplierId"
              clearable
              filterable
              placeholder="请选择"
              class="!w-[180px]"
            >
              <el-option
                v-for="item in selectData.supplierList"
                :key="item.id"
                :label="item.supplierName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="预备货：" prop="preStockStatus">
            <!-- 预备货 0否 1是 -->
            <el-select
              v-model="form.preStockStatus"
              placeholder="请选择"
              clearable
              class="!w-[180px]"
            >
              <el-option label="是" value="1" />
              <el-option label="否" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :icon="useRenderIcon('ri:search-line')"
              :loading="loading"
              @click="onSearch"
            >
              搜索
            </el-button>
            <el-button
              :icon="useRenderIcon(Refresh)"
              @click="resetForm(formRef)"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
        <PureTableBar title="" :columns="columns" @refresh="onSearch">
          <template #buttons>
            <el-button
              type="primary"
              :icon="useRenderIcon(AddFill)"
              @click="openDialog('新增')"
            >
              新增商品
            </el-button>

            <el-button
              plain
              type="primary"
              :disabled="selectedNum == 0"
              @click="onBatchStart(1)"
            >
              批量启用
            </el-button>
            <el-button
              plain
              type="danger"
              :disabled="selectedNum == 0"
              @click="onBatchStart(0)"
            >
              批量停用
            </el-button>
            <el-button type="primary" plain @click="showOptLog()">
              操作日志
            </el-button>
            <el-upload
              ref="uploadRef"
              :headers="{ accessToken: getToken() }"
              :http-request="handleUpload"
              :before-upload="beforeUpload"
              accept=".xls, .xlsx"
              action="no"
              class="mr-[10px] ml-[10px]"
              :show-file-list="false"
              :limit="1"
            >
              <el-button type="success">导入商品</el-button>
            </el-upload>
            <el-button @click="downTemp">下载模版</el-button>
          </template>
          <template v-slot="{ size, dynamicColumns }">
            <div class="goods-table">
              <pure-table
                ref="tableRef"
                row-key="id"
                adaptive
                :adaptiveConfig="{ offsetBottom: 108 }"
                align-whole="center"
                :loading="loading"
                :size="size"
                :data="dataList"
                :columns="dynamicColumns"
                :pagination="{ ...pagination, size }"
                show
                :row-class-name="iconHide"
                :header-cell-style="{
                  background: 'var(--el-fill-color-light)',
                  color: 'var(--el-text-color-primary)'
                }"
                @selection-change="handleSelectionChange"
                @page-size-change="handleSizeChange"
                @page-current-change="handleCurrentChange"
              >
                <template #expand="{ row }">
                  <div class="ml-[76px]">
                    <!-- ==================================== 子表格 =========================== -->
                    <pure-table
                      row-key="id"
                      class="bd-hide"
                      align-whole="center"
                      :show-header="false"
                      :data="row.goodsSpecList"
                      :columns="childColumns"
                    >
                      <!-- 规格名称 -->
                      <template #specName="scope">
                        <div class="flex items-center mr-[-12px]">
                          <ImageViewer
                            :src="scope.row.specImageJson || row.imageJson"
                          />
                          <div
                            class="ml-[5px] cursor-pointer flex-1 overflow-hidden whitespace-normal"
                          >
                            {{ scope.row.specName }}
                          </div>
                        </div>
                      </template>
                      <!-- 规格编码 -->
                      <template #specCode="{ row }">
                        <el-tooltip
                          effect="dark"
                          :content="row.specCode"
                          placement="top-start"
                        >
                          <div class="text-cut">{{ row.specCode }}</div>
                        </el-tooltip>
                      </template>
                      <!-- 规格条码 -->
                      <template #barCode="{ row }">
                        <el-tooltip effect="dark" placement="top-start">
                          <template #content>
                            <div>主条码: {{ row.barCode }}</div>
                            <div>
                              辅助条码:
                              {{
                                row.auxiliaryBraCodeList &&
                                row.auxiliaryBraCodeList.length > 0
                                  ? row.auxiliaryBraCodeList.join(", ")
                                  : "--"
                              }}
                            </div>
                          </template>
                          <div class="ml-[-10px] mr-[-10px]">
                            {{ row.barCode }}
                          </div>
                        </el-tooltip>
                      </template>
                      <template #operations="{ row, index }">
                        <el-button
                          class="reset-margin"
                          link
                          type="primary"
                          :size="size"
                          :icon="useRenderIcon(EditPen)"
                          @click="changeBrandPrice(row)"
                        >
                          关联品牌
                        </el-button>
                        <el-popconfirm
                          :title="`是否确认删除规格: '${row.specName}' ?`"
                          @confirm="handleDeleteSpec(row)"
                        >
                          <template #reference>
                            <el-button
                              class="reset-margin !ml-[5px]"
                              link
                              type="danger"
                              :disabled="index == 0"
                              :size="size"
                              :icon="useRenderIcon(Delete)"
                            >
                              删除
                            </el-button>
                          </template>
                        </el-popconfirm>
                      </template>
                    </pure-table>
                  </div>
                </template>
                <!-- 规格条码 -->
                <template #barCode="{ row }">
                  <template
                    v-if="row.goodsSpecList && row.goodsSpecList.length == 1"
                  >
                    <el-tooltip effect="dark" placement="top-start">
                      <template #content>
                        <div>主条码: {{ row.goodsSpecList[0].barCode }}</div>
                        <div>
                          辅助条码:
                          {{
                            row.goodsSpecList[0].auxiliaryBraCodeList &&
                            row.goodsSpecList[0].auxiliaryBraCodeList.length > 0
                              ? row.goodsSpecList[0].auxiliaryBraCodeList.join(
                                  ", "
                                )
                              : ""
                          }}
                        </div>
                      </template>
                      <div class="ml-[-10px] mr-[-10px]">
                        {{ row.goodsSpecList[0].barCode }}
                      </div>
                    </el-tooltip>
                  </template>
                </template>
                <template #operation="{ row }">
                  <el-button
                    class="reset-margin"
                    link
                    type="primary"
                    :size="size"
                    :icon="useRenderIcon(EditPen)"
                    @click="openDialog('修改', row)"
                  >
                    修改
                  </el-button>
                  <el-button
                    v-if="row.goodsSpecList && row.goodsSpecList.length == 1"
                    class="reset-margin !ml-[5px]"
                    link
                    type="primary"
                    :size="size"
                    :icon="useRenderIcon(EditPen)"
                    @click="changeBrandPrice(row.goodsSpecList[0])"
                  >
                    关联品牌
                  </el-button>
                  <el-popconfirm
                    :title="`是否确认删除商品: '${row.goodsName}' ?`"
                    @confirm="handleDelete(row)"
                  >
                    <template #reference>
                      <span>
                        <el-tooltip
                          class="box-item"
                          effect="dark"
                          content="启用状态商品不可删"
                          :disabled="row.goodsStatus == 0"
                          placement="top-start"
                        >
                          <el-button
                            class="reset-margin !ml-[5px]"
                            link
                            type="danger"
                            :disabled="row.goodsStatus == 1"
                            :size="size"
                            :icon="useRenderIcon(Delete)"
                          >
                            删除
                          </el-button>
                        </el-tooltip>
                      </span>
                    </template>
                  </el-popconfirm>
                </template>
              </pure-table>
            </div>
          </template>
        </PureTableBar>
      </div>
    </div>
  </div>
</template>
<style lang="scss" scoped>
:deep(.bd-hide .el-table--fit .el-table__inner-wrapper:before) {
  background-color: #fff;
}
:deep(.icon-no .el-table__expand-icon) {
  display: none;
}
</style>
